package com.podcstr.controller;

import com.podcstr.entity.MediaFile;
import com.podcstr.service.MediaFileService;
import org.apache.log4j.Logger;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Named;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author azim
 * @since 5/26/13 
 */

@Named
@ApplicationScoped
public class MediaFileController {

    private final Logger log = Logger.getLogger(PodcastController.class.getName());

    @EJB
    private MediaFileService mediaFileService;

    public StreamedContent getMediaFile() throws IOException {

        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the image. Get ID value from actual request param.
            String id = context.getExternalContext().getRequestParameterMap().get("id");
            MediaFile mediaFile = mediaFileService.findById(Long.valueOf(id));
            StreamedContent streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(mediaFile.getContent()), mediaFile.getContentType(), mediaFile.getName());
            return streamedContent;
        }
    }
}
